from functools import wraps

from flask import render_template, request, flash, redirect, url_for, session
from flask_login import login_required, current_user, login_user, logout_user

from app import app,login_manager
from app.model import *
from flask import jsonify, request
from db import db
import uuid
from flask import render_template


# @app.route('/record', methods=['GET'])
def get_record():
    print("----------------get_record---------------------")
    id = request.args.get('id')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    user_id = request.args.get('uer_id')
    user = User.query.filter_by(id=user_id).first() if user_id else None

    if id:
        records = Record.query.filter_by(id=id).paginate(page=page, per_page=per_page)
    else:
        records = Record.query.paginate(page=page, per_page=per_page)
    eq_list = []
    for eq_obj in records.items:
        eq = Equipment.query.filter_by(equipment_id=eq_obj.equipment_id).first()
        if eq:
            eq_list.append(eq.get())
    record_data = [eq.get() for eq in records.items]
    return {
        "r_list": record_data,
        "user": user.get() if user else [],
        'eq_list': eq_list,
        'total': records.total,
        'pages': records.pages,
        'status': 200
    }


@app.route('/record/insert', methods=['POST'])
def insert_record():
    print("----------------insert_record---------------------")
    r_list = request.json.get("r_list", [])
    r_objs = [Record(
        id=uuid.uuid4(),
        user_id=data.get('user_id'),
        equipment_id=data.get('equipment_id'),
        creat_time=data.get('creat_time'),
        type=data.get('type'),
        effect=data.get('effect'),
    ) for data in r_list]
    db.session.add_all(r_objs)
    try:
        db.session.commit()
        return jsonify({
            'msg': '插入成功'
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 400
